﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using LINQPad.Extensibility.DataContext;
using LINQPad.OpenAccess.Helpers;
using LINQPad.OpenAccess.Services.Descriptors;
using LINQPad.OpenAccess.Settings;

namespace LINQPad.OpenAccess.Services
{
    /// <summary>
    /// <see cref="IDataContextConnectionDescriptionProvider"/>
    /// </summary>
    public class DataContextConnectionDescriptionProvider : IDataContextConnectionDescriptionProvider
    {
        #region Private

        #region - Vars

        [DebuggerBrowsable( DebuggerBrowsableState.Never )]
        private readonly IConnectionDescriptor[] _connectionDescriptors;

        #endregion

        #endregion

        #region Public

        #region - Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="DataContextConnectionDescriptionProvider" /> class.
        /// </summary>
        /// <param name="connectionDescriptors">The connection descriptors.</param>
        public DataContextConnectionDescriptionProvider( IEnumerable<IConnectionDescriptor> connectionDescriptors )
        {
            Guard.ArgumentNotNull( connectionDescriptors, "connectionDescriptors" );
            this._connectionDescriptors = connectionDescriptors.OrderByDescending( p => p.Priority ).ToArray( );
        }

        #endregion

        #endregion

        #region IConnectionDescriptionProvider Members

        /// <summary>
        /// Gets the description.
        /// </summary>
        /// <param name="connectionInfo">The connection info.</param>
        /// <param name="driverSettings">The driver settings.</param>
        /// <returns>
        /// The description.
        /// </returns>
        public string GetDescription( IConnectionInfo connectionInfo, DriverSettings driverSettings = null )
        {
            if ( connectionInfo == null )
                return null;

            for ( int i = 0; i < this._connectionDescriptors.Length; i++ )
                if ( this._connectionDescriptors[i].CanDescribe( connectionInfo, driverSettings ) )
                    return this._connectionDescriptors[i].Describe( connectionInfo, driverSettings );

            return connectionInfo.CustomTypeInfo == null ? null : connectionInfo.CustomTypeInfo.GetCustomTypeDescription( );
        }

        #endregion
    }
}
